package cn.gok.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;

/**
 * @author: 鸭鸭
 * @ClassName:FTPUtil
 * @Package:cn.gok.util
 * @Description:ftp上传下载工具类
 * @date: 2021/8/10
 * @time: 17:02
 */
public class FTPUtil {
    /**
     *  ftp服务器的地址
     */
    private String ftpIP = "localhost";
    /**
     *  ftp服务器的用户名
     */
    private String username = "root";
    /**
     *  ftp服务器的密码
     */
    private String password = "123456";


    private FTPClient ftpClient;


    /**
     连接ftp服务器，如果连接成功，返回true，否则返回false
     */
    private boolean connectFTPServer() throws IOException {

        //创建客户端对象
        ftpClient = new FTPClient();

        //连接ftp服务器
        ftpClient.connect(ftpIP);

        //登录ftp服务器
        boolean login = ftpClient.login(username, password);

        return login;
    }


    public boolean uploadFile(File file) throws IOException {

        boolean isUpload = false;
        FileInputStream inputStream = null;

        try {
            if (connectFTPServer()){

                //切换工作空间至img文件夹
                ftpClient.changeWorkingDirectory("img");
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("utf-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();



                inputStream = new FileInputStream(file);

                //上传至ftp服务器，输入文件名和 输入流
                isUpload = ftpClient.storeFile(file.getName(), inputStream);
            }
        }catch (IOException e){
            e.printStackTrace();
            isUpload = false;
        }finally{
            inputStream.close();
            ftpClient.disconnect();
        }
        return isUpload;
    }

}
